/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package aic.lists;

import aic.beans.Item;
import aic.beans.Order;
import aic.misc.DebugPrint;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

public class ShippingList {

    private static List<Item> shippingList = Collections.synchronizedList(new LinkedList<Item>());

    /**
     * Adds an Item to "shippingList" and starts a thread that waits until the
     * Item is successfully shipped
     *
     * @param item Item object
     */
    public static void add(Item item) {
        DebugPrint.println("Entering add");
        shippingList.add(item);
        new ShippingListThread(item).start();
    }

    /**
     * Prints out a list of all Items within "shippingList"
     */
    public static void printList() {
        Iterator it = shippingList.iterator();

        while (it.hasNext()) {
            System.out.println(">>list value (shippingList): " + it.next());
        }
    }

    public static boolean is_finished(Order order) {
        DebugPrint.println("Checking if items are still in the list of "+order.getId()+"..");
        List<Item> items = order.getItems();

        for (Item item : items) {
            if (shippingList.contains(item)) {
                DebugPrint.println("..item still not shipped: "+item);
                return false;
            }
        }

        DebugPrint.println("..all items shipped!");
        return true;
    }

    /**
     * Removes a certain Item from "shippedList"
     *
     * @param item Item object
     * @return true if the operation was successful
     */
    static boolean removeFromList(Item item) {
        return shippingList.remove(item);
    }
}

class ShippingListThread extends Thread {

    private Item item;

    ShippingListThread(Item item) {
        this.item = item;
    }

    /**
     * Waits 5-10 seconds before removing an Item from "shippingList"
     * and adding it to "ShippedList"
     */
    public void run() {
        try {
            // wait 5 to 10 seconds
            long sleepingTime = (long) (Math.random() * 5000 + 5000);
            DebugPrint.println("Shipping process started..");
            sleep(sleepingTime);
        } catch (InterruptedException ex) {
            Logger.getLogger(ShippingListThread.class.getName()).log(Level.SEVERE, null, ex);
        }

        boolean shipped = ShippingList.removeFromList(item) && ShippedList.add(item);
        DebugPrint.println("Shipping for item '"+item.getProduct_id()+"' done: "+shipped);

    }
}
